<template>
  <div class="search">
    <div class="wrap">
      <el-table :data="songs" stripe>
        <el-table-column label="歌曲名称" prop="name"></el-table-column>
        <el-table-column label="歌手" prop="artist"></el-table-column>
        <el-table-column label="专辑" prop="album"></el-table-column>
        <el-table-column label="歌曲时长" prop="duration"></el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { useRoute } from 'vue-router';
import { ref, onMounted, watch } from 'vue';
import axios from 'axios';

const route = useRoute();
const keywords = route.query.keywords;
console.log(keywords);

const songs = ref([]);

function formatTime(time) {
  //time是毫秒数,要除以1000 => 04:12
  let mins = Math.floor(time / 1000 / 60); //分钟
  mins = mins < 10 ? '0' + mins : mins;

  let secs = Math.floor((time / 1000) % 60); //秒
  secs = secs < 10 ? '0' + secs : secs;

  return `${mins}:${secs}`;
}

//调用接口 http://localhost:3001/search?keywords=xxx
//发送请求
const fetchSongs = async (keywords) => {
  try {
    const res = await axios.get(
      `http://localhost:3001/search?keywords=${keywords}`
    );
    songs.value = res.data.result.songs.map((song) => {
      return {
        name: song.name,
        artist: song.artists[0].name,
        album: song.album.name,
        duration: formatTime(song.duration),
      };
    });
  } catch (error) {
    console.error(error);
  }
};

onMounted(() => {
  fetchSongs(keywords);
});

watch(route, () => {
  console.log(route);
  const keywords = route.query.keywords;
  fetchSongs(keywords);
});
</script>

<style lang="scss" scoped>
.search {
  min-height: 700px;
  background-color: #eee;
}
// :deep是scss语法下的深度选择器, 加上scoped以后, 可以穿透选择子组件的样式
:deep(.cell) {
  white-space: nowrap; // 不换行
  overflow: hidden; // 隐藏超出的内容
  text-overflow: ellipsis; // 省略号显示
}
</style>
